import re
import time
from random import randint

from telethon.tl.functions.channels import (JoinChannelRequest,
                                            LeaveChannelRequest)

from Browser import browser
from Console import console
from Database import add_group, delete_old_connections
from Settings import (ACTIVATE_AD_MESSAGE, ACTIVATE_BOTS_MESSAGE,
                      ACTIVATE_GROUPS_MESSAGE, AD_MESSAGE, BOT_MESSAGE,
                      CHANNEL_MESSAGE, DELAY_AFTER_ERROR, GROUP_MESSAGE,
                      MAX_FAILURES, STANDART_DELAY)


async def find_and_forward(client, bot_chat, bot_to_activate):
    try:
        await client.send_message(bot_to_activate[0], '/start')
    except Exception as e:
        console.error("Message wasn't sent due to error: {}".format(e))
        raise Exception

    time.sleep(2)
    bot_to_activate_chat = None
    
    bot_to_activate_chat=await client.find_dialog(bot_to_activate[1])
    messages = await client.get_messages(bot_to_activate_chat, limit=1)
    for message in messages:
                   
        await client.forward_messages(bot_chat, message)
        time.sleep(2)
        if message.text == '/start':
            await client.delete_dialog(bot_to_activate_chat)
            return False 
    time.sleep(3)

    await client.delete_dialog(bot_to_activate_chat)


async def do_tasks_ad_click(client,ltc_bot_chat,proxy=None):
    doge_url=""
    prev_url='LTC'
    flag=0 
    await client.send_message(ltc_bot_chat.title, ACTIVATE_AD_MESSAGE)
    time.sleep(randint(2,5))
    while True:
        for message in await client.get_messages(ltc_bot_chat, limit=1):
            if bool(re.search(AD_MESSAGE, message.message)):
                if flag==0:
                    console.info("="*10+f"Next task"+"="*10)
                else:
                    console.info("="*10+f"Attemp N.{flag}"+"="*10)
                doge_url = client.get_url_from_button(message)
                console.info(f"Found Doge-link {doge_url}")
                if (prev_url==doge_url) and flag==MAX_FAILURES:
                    time.sleep(2)
                    await message.click(2)
                    console.info("Skipping task due max failures")
                    flag=0
                else:
                    try:
                        browser.getURL(doge_url)
                        
                    except Exception as e:
                        console.warning("Something wrong with browser: {}".format(e))
                        prev_url=doge_url
                        flag+=1
                        continue
                    flag=0
            elif re.search("Sorry, this task is", message.message):
                await client.send_message(ltc_bot_chat.title, "/visit")
            elif re.search("Sorry, there are no new ads available.", message.message):
                return
            else:
                break

async def do_tasks_bots(client, ltc_bot_chat, proxy=None):
    flag=0 #at second time skipped
    await client.send_message(ltc_bot_chat.title, ACTIVATE_BOTS_MESSAGE)
    time.sleep(2)
    
    
    while True:
        messages = await client.get_messages(ltc_bot_chat, limit=1)
        for message in messages:
            
            if bool(re.search(BOT_MESSAGE, message.message)):
                if flag==0:
                    console.info("="*10+f"Next task"+"="*10)
                else:
                    console.info("="*10+f"Attemp N.{flag}"+"="*10)
                doge_url = client.get_url_from_button(message)
                console.info(f"Found Doge-link {doge_url}")
                if flag==MAX_FAILURES:
                    
                    time.sleep(2)
                    await message.click(2)
                    console.info("Skipping task due max failures")
                    flag=0
                else:
                    try:
                        bot_to_activate = browser.getBotUrl(doge_url)
                    except Exception as e:
                            console.error("Something wrong with browser: {}".format(e))
                            flag+=1
                            continue
                    flag=0
            elif re.search("Sorry, this task is", message.message):
                await client.send_message(ltc_bot_chat.title, "/bots")

            elif re.search("Sorry, there are no new", message.message):

                return
            else:
                console.error(f"Something went wrong, waiting..."+f"{message.message}")
                time.sleep(DELAY_AFTER_ERROR)
                await client.send_message(ltc_bot_chat.title, ACTIVATE_BOTS_MESSAGE)
                time.sleep(5)
                
                flag+=1
                
                break
            try:
                if bot_to_activate[0]:
                        if await find_and_forward(client, ltc_bot_chat, bot_to_activate)==False:
                            await message.click(2)
                            console.info("Skipping because of a bot that doesn't work")
                else:
                    await message.click(2)
                    console.info("Skipping because of a bot that doesn't work")
            except:
                await message.click(2)
                console.info("Skipping because of a bot that doesn't work (xD)")
                        
async def _join_group(client, bot_chat, group_to_join, message):
    
    
    try:
        await client(JoinChannelRequest(channel=group_to_join[1]))
    except:
        return False
    time.sleep(3)
    try:
        await message.click(1)
    except Exception as e:
        console.error("Error with clicking on button: {}".format(e))

    time.sleep(1)
    messages = await client.get_messages(bot_chat, limit=2)
    stay_in_group = 0
    for el in messages:
        if "Success" in el.message:
            pos = el.message.index("at least")

            stay_in_group = int(el.message[pos + 9:el.message[pos + 9:].index(' ') + pos + 9])
    if stay_in_group!=0:
        add_group(client,group_to_join[0],group_to_join[1],stay_in_group)
    else:
        return False
    time.sleep(2)
async def do_tasks_groups(client, ltc_bot_chat, proxy=None):
    await client.send_message(ltc_bot_chat.title, ACTIVATE_GROUPS_MESSAGE)
    time.sleep(3)
    failures = 0
    url = " "
    pr_url = "some text"
    first_time = False
    skipped = False
    tries = 0
    group_to_join = [None, None]

    while True:
        #console.info(str(tries))
        messages = await client.get_messages(ltc_bot_chat, limit=1)
        for message in messages:

            if re.search(CHANNEL_MESSAGE, message.message) or re.search(GROUP_MESSAGE, message.message):
                url = client.get_url_from_button(message)
                console.info(f"Found Doge-link {url}")

                if url != pr_url:
                    tries = 0

                if url == pr_url and tries > 1:
                    await message.click(3)  # clicking on a fourth button in message
                    console.info("Skiping")
                    skipped = True
                    tries = 0
                    time.sleep(2)


                else:
                    try:
                        group_to_join = browser.getGroupUrl(url)

                    except Exception as e:
                        console.error("Something wrong with browser: {}".format(e))
                    if first_time:
                        first_time = False

                    if skipped:
                        skipped = False
                    pr_url = url
                    tries += 1
                time.sleep(3)

            elif re.search("Sorry, this task is", message.message):
                await client.send_message(ltc_bot_chat.title, "/bots")

            elif re.search("Sorry, there are no new", message.message):

                return
            elif re.search("We cannot find you in the channel", message.message):
                tries = 0 #just retrying
                await client.delete_dialog(await client.find_dialog(group_to_join[0]))
                break 

            else:
                failures += 1
                console.error("Something went wrong, waiting...")
                console.info(message.message)

                time.sleep(DELAY_AFTER_ERROR)

                await client.send_message(ltc_bot_chat.title, ACTIVATE_GROUPS_MESSAGE)
                time.sleep(10)
                if failures > MAX_FAILURES:
                    console.error("Exiting because of max failures")

                    return
                continue
        
            if group_to_join[0] and group_to_join[1]:
                
                if await _join_group(client, ltc_bot_chat, group_to_join, message)==False:
                    await message.click(3)  # clicking on a fourth button in message
                    console.info("Skiping")
                    tries = 0
            else:
                await message.click(3)  # clicking on a fourth button in message
                console.info("Skiping")
                tries = 0